import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_router.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';

class ShoppingCartButton extends StatefulWidget {
  const ShoppingCartButton({super.key});

  @override
  State<ShoppingCartButton> createState() => _ShoppingCartButtonState();
}

class _ShoppingCartButtonState extends State<ShoppingCartButton> {
  int _courseCount = 0;

  @override
  void initState() {
    super.initState();
    // 初始化时更新课程数量
    _courseCount = AccountInfo.shared.purchasingCourses.length;
    AccountInfo.shared.userBriefNotifier.addListener(_updateCourseCount);
  }

  @override
  void dispose() {
    AccountInfo.shared.userBriefNotifier.removeListener(_updateCourseCount);
    super.dispose();
  }

  // 更新课程数量
  void _updateCourseCount() {
    final count = AccountInfo.shared.purchasingCourses.length;
    if (_courseCount != count) {
      setState(() {
        _courseCount = count;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        IconButton(
          // 导航到购物车页面
          onPressed: () {
            context.pushNamed(AppRouter.kShoppingCart);
          },
          icon: const Icon(Icons.shopping_cart_outlined, size: 22),
          padding: const EdgeInsets.all(0),
        ),
        if (_courseCount > 0)
          Positioned(
            // right: -6,
            // top: -6,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(1),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(8),
              ),
              constraints: const BoxConstraints(minWidth: 16, minHeight: 16),
              child: Center(
                child: Text(
                  (_courseCount > 99 ? '99+' : '$_courseCount'),
                  style: const TextStyle(color: Colors.white, fontSize: 11),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
      ],
    );
  }
}
